package org;

import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;

import user.User;

public class UserIterator implements Iterator<User>{
	
@SuppressWarnings("unused")
private FileUtils data;
@SuppressWarnings("unused")
private int total;
private RandomAccessFile iof;
private long pos;

	UserIterator(FileUtils data) {
		this.data=data;
		total=data.getUserNumber();
		iof=data.getFile();
	}

	@Override
	public boolean hasNext() {
		try {
			pos=iof.getFilePointer();
			iof.readInt();
			iof.seek(pos);
		}
		catch(IOException iox) {
			System.out.println("End of file achieved. No Users left. Iterator back to start.");
			iof=null;
			return false;
		}
		return true;
	}

	@Override
	public User next() throws NoSuchElementException {
		byte[] bf;
		String name=null,password=null;
		try {
			//throw Exception if iterator is finished
			if(iof==null) {
				throw new NoSuchElementException("Iterator is already finished!");
			}
			
			int id=iof.readInt();
			bf=new byte[iof.readInt()];
			iof.read(bf,0,bf.length);
			name=new String(bf);
			bf=new byte[iof.readInt()];
			iof.read(bf,0,bf.length);
			password=new String(bf);
			password=PWCrypt.unscramblePW(password,name,id);
			return User.reconstruct(id, name, password);
		}
		catch (EOFException eofx) {
			System.err.println("End of file achieved");
		}
		catch (IOException iox) {
			System.err.println("could not parse data: IO Error occurred");
			//iox.printStackTrace();
		}
		return null;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

}
